from mirai import GroupMessage, Mirai, Image, Plain, MessageChain, At

from robot_core.preset_content import PresetContent
from robot_service.error_message import ErrorHelper
from robot_service.message_helper import send_message, image_persistence


class MessageTrigger:
    # 信息触发器 聊天信息会触发此类中的方法

    def __init__(self, bot: Mirai):
        self.__bot = bot
        self.__error_helper = ErrorHelper()
        self.__preset_content = PresetContent()

        # 消息缓存字典
        # 数据结构为
        # dict:{
        #   "群id":[
        #       {
        #           "id": 消息发送者id,
        #           "event": event
        #       }
        #    ]
        # }
        self.__message_cache = dict()

    async def keyword_capture(self, event):
        # TODO 除了本机器人 也可以屏蔽一些已知的机器人qq
        if event.sender.id == self.__bot.qq or event.sender.id == 2796442902:
            return
        # 在这里捕获消息
        # 并根据消息来源类型分发到不同的触发器
        if isinstance(event, GroupMessage):
            # ai_core_trigger = await self.ai_core(event, False)
            emojis_trigger = await self.__emojis_trigger(event, False)
            train_pass_trigger = await self.__train_pass(event, emojis_trigger)
            repeater_trigger = await self.__repeater_trigger(event, train_pass_trigger)
            # return ai_core_trigger or emojis_trigger \
            return emojis_trigger \
                or train_pass_trigger or repeater_trigger

    # async def ai_core(self, event, has_triggered: bool):
    #     if has_triggered:
    #         return True
    #     # 人工智能对话代码 估值一个亿
    #     at_list = event.message_chain[At]
    #     for at in at_list:
    #         if at.target == self.__bot.qq:
    #             message = MessageChain()
    #             for plain in event.message_chain[Plain]:
    #                 if plain.text.strip() == "":
    #                     break
    #                 result = plain.text.replace("嗎", "吗") \
    #                     .replace("吗", "") \
    #                     .replace("？", "！") \
    #                     .replace("?", "！")
    #                 if "是不是" in result:
    #                     result.replace("是不是", "不是")
    #                 if "會不會" in result or "会不会" in result:
    #                     result.replace("會不會", "会不会")
    #                     result.replace("会不会", "不会")
    #                 result = result.strip()
    #                 if result != "":
    #                     message.append(result)
    #             if len(message[Plain]) > 0:
    #                 await send_message(self.__bot, event, message)
    #                 return True
    #             return False

    async def __emojis_trigger(self, event, has_triggered: bool):
        if has_triggered:
            return True
        # TODO 此方法应该在上级封装一层, 如果命中关键词 再进入目标方法进行操作
        chain_list = event.message_chain[Plain]
        # TODO 拆分两个选项
        for message in chain_list:
            text = message.text
            for keywords, image_path in self.__preset_content.image_dict.items():
                if keywords in text:
                    await send_message(self.__bot, event, MessageChain([Image(path=image_path)]))
                    return True

    async def __train_pass(self, event, has_triggered: bool):
        if has_triggered:
            return True
        chain_list = event.message_chain[Plain]
        for message in chain_list:
            text = message.text.replace("嗚", "呜")
            # TODO 此方法应该在上级封装一层, 如果命中关键词 再进入目标方法进行操作
            if "呜" in text:
                if "呜呜" in text:
                    await send_message(self.__bot, event, MessageChain([Plain("摸摸头,没关系的哦"), Image(path=self.__preset_content.image_dict["摸摸头"])]))
                    return True
                if "不准呜" in text:
                    if text[0:2] == "不准":
                        await send_message(self.__bot, event, MessageChain([Plain(f"不准{text}")]))
                    else:
                        await send_message(self.__bot, event, MessageChain([Plain("不准不准呜!")]))
                    return True
                if "嗷呜" in text or "喵呜" in text:
                    await send_message(self.__bot, event, MessageChain([Plain("不准呜!")]))
                    return True

    async def __repeater_trigger(self, event, has_triggered: bool):
        if has_triggered:
            return True
        # 复读机触发器 方法
        group_id = str(event.sender.group.id)
        sender_id = str(event.sender.id)
        if group_id not in self.__message_cache.keys():
            self.__message_cache[group_id] = list()
            self.__message_cache[group_id].append({"id": sender_id, "event": event})
            return False

        group_message: list
        group_message = self.__message_cache.get(group_id)
        group_message.append({"id": sender_id, "event": event})

        # 如果这个群里已经有三条信息缓存
        if len(group_message) == 3:
            event_list: list
            event_list = [x.get('event') for x in group_message]
            message_chain_list = [msg.message_chain[:] for msg in event_list]
            for message_chain in message_chain_list:
                message_chain.pop(0)
            last_event = event_list[-1]
            chain = last_event.message_chain[:]
            chain.pop(0)
            if message_chain_list.count(chain) == 3:
                new_chain = await image_persistence(last_event.message_chain)
                await send_message(self.__bot, event, new_chain)
                group_message.clear()
                return True
            else:
                group_message.pop(0)
        # else:
        #     # 随机复读
        #     if random.randint(1, 9999) > 9500:
        #         new_chain = await image_persistence(event.message_chain)
        #         await send_message(self.__bot, event, new_chain)
        #         return True
        #     if len(group_message) > 3:
        #         group_message.pop(0)
        #         return False
        #     return False
